package qdrant

import (
	"context"
	"time"

	qdrant_client "github.com/qdrant/go-client/qdrant"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/encoding/gzip" // Install the gzip compressor
)

var initTimeout = time.Second * 5

type QDrantConfig struct {
	Host string `yaml:"host" mapstructure:"host"`
}

func init() {
	grpc.UseCompressor(gzip.Name)
}

func NewQdrantClient(config QDrantConfig) *grpc.ClientConn {
	dialCtx, cancel := context.WithTimeout(context.Background(), initTimeout)
	defer cancel()

	conn, err := grpc.DialContext(dialCtx, config.Host,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithBlock(),
	)
	if err != nil {
		panic(err)
	}
	return conn
}

func MakeConditionByMap(data map[string]interface{}) []*qdrant_client.Condition {
	var conditions []*qdrant_client.Condition

	for key, value := range data {
		var condition *qdrant_client.Condition

		switch v := value.(type) {
		case string:
			condition = &qdrant_client.Condition{
				ConditionOneOf: &qdrant_client.Condition_Field{
					Field: &qdrant_client.FieldCondition{
						Key: key,
						Match: &qdrant_client.Match{
							MatchValue: &qdrant_client.Match_Text{
								Text: v,
							},
						},
					},
				},
			}
		case bool:
			condition = &qdrant_client.Condition{
				ConditionOneOf: &qdrant_client.Condition_Field{
					Field: &qdrant_client.FieldCondition{
						Key: key,
						Match: &qdrant_client.Match{
							MatchValue: &qdrant_client.Match_Boolean{
								Boolean: v,
							},
						},
					},
				},
			}
			// 可以根据需要添加其他类型的处理
		}

		if condition != nil {
			conditions = append(conditions, condition)
		}
	}

	return conditions
}
